package com.weishuang.monitor.leader.config.validated;

import cn.hutool.core.util.StrUtil;
import com.weishuang.monitor.leader.commons.entity.Result;
import com.weishuang.monitor.leader.commons.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class ValidatedExceptionConfiguration {

    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public Result vaildatedException(Exception e) {
        BindingResult bindingResult;
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        } else {
            bindingResult = ((BindException) e).getBindingResult();
        }
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        String collect = fieldErrors.stream().map(ex -> ex.getDefaultMessage()).collect(Collectors.joining(StrUtil.COMMA));
        log.debug(collect);
        return ResultUtils.info(collect);
    }

}
